﻿-- Function: public.workflowtabsel(character varying, text, character varying)

-- DROP FUNCTION public.workflowtabsel(character varying, text, character varying);

CREATE OR REPLACE FUNCTION public.workflowtabsel(
    p_bill character varying,
    p_condition text,
    p_fieldsel character varying,
    p_field character varying,
    p_fieldid integer)
  RETURNS integer AS
$BODY$
declare  
    v_cnt integer;
    v_sql text;
begin  

   v_sql := 'select COALESCE(min(' || p_fieldsel || '),0) from public.' || p_bill || ' where  ' || p_field || ' = '|| p_fieldid;
   if trim(p_condition) !='' then
	v_sql := v_sql || ' and (' || p_condition || ')';
   end if;
   execute  v_sql into v_cnt; 
   RETURN v_cnt::integer; 
END;  
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
